import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Row, Col, Table, Form, Input, message, Button, Select, Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { connect } from 'umi';
import CategoryTree from '@/components/CategoryTree';

const { confirm } = Modal;
const columns = [
    {
        title: '编号',
        dataIndex: 'id',
        key: 'id',
        width: 70,
    },
    {
        title: '角色',
        dataIndex: 'displayName',
        key: 'displayName',
    },
];
class ViewAuth extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            loading: false,
            dataSource: [],
            datas: {},
            Permissions: [],
            menuPermission: ['0-0-0'],
        }
    }
    formRef: any = React.createRef();
    componentDidMount() {
        this.fetchRoles();
        this.fetchPermission();
    }
    fetchRoles = () => {
        this.props.dispatch({
            type: "Abp/getAll",
            payload: { SkipCount: 0, MaxResultCount: 100 },
            control: 'Role',
        }).then(() => {
            var resp = this.props.response.result;
            if (resp) {
                var dataSource = resp.items;
                this.setState({ loading: false, dataSource })
            }
        });
    }
    fetchPermission = () => {
        this.props.dispatch({
            type: "Abp/getAllPermissions",
        }).then(() => {
            var resp = this.props.response.result;
            if (resp) {
                var Permissions = resp.items;
                this.setState({ Permissions })
            }
        });
    }
    ResetForm = () => {
        var data = {
            id: 0,
        }
        this.setState({ datas: data });
        this.formRef.current.resetFields();
    }
    onFinish = (values: any) => {
        var act = "Abp/create";
        if (values.Role.id > 0) {
            act = "Abp/update";
        }
        values.Role.menuPermission = values.Role.menuPermission.join(',');
        this.props.dispatch({
            type: act,
            payload: values.Role,
            control: 'Role',
        }).then(() => {
            var resp = this.props.response;
            if (resp.success) {
                message.success('保存成功！');
                this.fetchRoles();
            }
            else {
                message.error('保存错误，请联系管理员');
            }
        });
    };
    handleDel = () => {
        const { datas } = this.state;
        if (datas.name == "admin") {
            message.error('Admin不允许删除！');
        }
        else {
            this.props.dispatch({
                type: "Abp/delete",
                payload: { Id: datas.id },
                control: 'Role',
            }).then(() => {
                var resp = this.props.response;
                if (resp.success) {
                    message.success('删除成功！');
                    this.fetchRoles();
                    this.formRef.current.resetFields();
                }
                else {
                    message.error('删除错误，请联系管理员！');
                }
            })
        }

    }
    showConfirm = () => {
        var _this = this;
        confirm({
            title: '警告',
            icon: <ExclamationCircleOutlined />,
            content: '删除后将不可恢复，确定删除？',
            onOk() {
                _this.handleDel();
            },
            onCancel() { },
        });
    }
    render() {
        const { dataSource, datas, Permissions } = this.state;
        const rowSelection = {
            onChange: (selectedRowKeys: any, selectedRows: any) => {
                var datas = selectedRows[0];
                this.setState({ datas });
                try {
                    if (datas.menuPermission) {
                        datas.menuPermission = datas.menuPermission?.split(',')
                    }
                }
                catch {
                    console.log('menuPermission.split error');
                }
                this.formRef.current.setFieldsValue({ Role: datas });
            },
            getCheckboxProps: (record: any) => ({
                //disabled: record.name === 'Admin',
                name: record.name,
            }),
        };
        const layout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 18 },
        };
        return (
            <PageHeaderWrapper title={false}>
                <Row gutter={16}>
                    <Col span={6}>
                        <Card title="角色列表">
                            <Table
                                rowKey="id"
                                rowSelection={{
                                    type: 'radio',
                                    ...rowSelection,
                                }}
                                dataSource={dataSource}
                                columns={columns}
                                pagination={false} />
                        </Card>
                    </Col>
                    <Col span={18}>
                        <Card title="角色明细">
                            <Form {...layout} ref={this.formRef} onFinish={this.onFinish} >
                                <div style={{ display: 'none' }}>
                                    <Form.Item
                                        label="id"
                                        name={['Role', 'id']}>
                                        <Input />
                                    </Form.Item>
                                </div>
                                <Form.Item
                                    name={['Role', 'name']}
                                    label="角色名"
                                    rules={[{ required: true, message: "请输入角色名" }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item
                                    name={['Role', 'displayName']}
                                    label="显示名"
                                    rules={[{ required: true, message: "请输入显示名" }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item
                                    name={['Role', 'description']}
                                    label="描述">
                                    <Input.TextArea />
                                </Form.Item>
                                <Form.Item label="模块权限" name={['Role', 'permissions']}>
                                    <Select mode="multiple" placeholder="请选择权限" allowClear >
                                        {
                                            Permissions.map((item: any, key: any) => {
                                                return (<Select.Option key={key} value={item.name}>{item.displayName}</Select.Option>)
                                            })
                                        }

                                    </Select>
                                </Form.Item>
                                <CategoryTree multiple={true} layout="Menu" width={300} name={['Role', 'menuPermission']} label="菜单权限" />
                                <Form.Item wrapperCol={{ ...layout.wrapperCol, offset: 4 }}>
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                        loading={this.state.loading}
                                    >保存</Button>
                                    <Button onClick={this.ResetForm} style={{ marginLeft: 10 }}>重设</Button>
                                    <Button danger
                                        onClick={this.showConfirm}
                                        disabled={datas.id == 0 || !datas.id}
                                        style={{ marginLeft: 10 }}>删除</Button>
                                </Form.Item>
                            </Form>
                        </Card>
                    </Col>
                </Row>

            </PageHeaderWrapper>
        )
    }
}
export default connect(({ Abp }: API.IConnectState) => ({
    currentUser: Abp.currentUser,
    response: Abp.response,
}))(ViewAuth);